﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;
using Utility;
using Utility.Graphic;
using Utility.Random;

namespace TerrainSystem
{
	public static class WarFogManager
	{
		static float height = 0;
		static string layer = "WarFog";

		static List<HashSet<MashInstanceDrawer>> _drawerSet_List = new List<HashSet<MashInstanceDrawer>> ();
		
		static WarFogManager ()
		{
			GameObject go = InternalResources.WarFog;
			m_inst = go.transform.localToWorldMatrix;

			foreach (var warFog_Obj in InternalResources.WarFog_List)
			{
				var hashSet = new HashSet<MashInstanceDrawer> ();
				foreach (Transform child in warFog_Obj.GetComponentsInChildren<Transform>())
				{
					//Debug.Log (child.name);
					var mesh = child.GetComponent<MeshFilter> ()?.sharedMesh;
					var material = child.GetComponent<Renderer> ()?.sharedMaterial;
					if (mesh && material)
					{
						var drawer1 = new MashInstanceDrawer ()
						{
							mesh = mesh,
							material = material,
							castShadows = ShadowCastingMode.Off,
							recieveShadows = false,
							lightProbeUsage = LightProbeUsage.Off,
							layer = LayerMask.NameToLayer (layer),
							originalMatrix4x4 = child.localToWorldMatrix,
							fogGoIndex = SystemRandom.Inst.GetInt (0, InternalResources.WarFog_List.Count)
						};
						hashSet.Add (drawer1);
					}
				}
				_drawerSet_List.Add (hashSet);
			}
			//Debug.Log (Matrix4x4.identity);
//Debug.Log (m_inst);
			drawer = new MashInstanceDrawer ()
			{
				mesh = go.GetComponent<MeshFilter> ().sharedMesh,
				material = go.GetComponent<Renderer> ().sharedMaterial,
				castShadows = ShadowCastingMode.Off,
				recieveShadows = false,
				lightProbeUsage = LightProbeUsage.Off,
				layer = LayerMask.NameToLayer (layer),
			};
		}

		static Matrix4x4 m_inst;
		static MashInstanceDrawer drawer;

		static Vector3 CoordToPosition (Vector2Int coord, Vector3 center)
		{
			return center + new Vector3 (coord.x, height, coord.y);
		}

		public static void Draw (IEnumerable<Vector2Int> coords, Vector3 center)
		{
			Matrix4x4 Getter (Vector2Int coord) => Matrix4x4.Translate (CoordToPosition (coord, center))* m_inst;
			drawer.Draw (coords, Getter);
			
//			Matrix4x4 Getter (Vector2Int coord) => Matrix4x4.Translate (CoordToPosition (coord, center))/* * m_inst*/;
//			var groups =  coords.GroupBy (coord => (coord.x + coord.y) % 4);
//			foreach (var group in groups)
//			{
//				//Debug.Log (group.Key);
//				var drawerSet = _drawerSet_List.TryGet (Mathf.Abs (group.Key));
//				//Debug.Log (_drawerSet_List.IndexOf (drawerSet));
//				if (drawerSet != null)
//				{
//					//Debug.Log ($"drawerSet.Count: {drawerSet.Count}");
//					foreach (var drawer in drawerSet)
//					{
//						drawer.Draw (group, Getter);
//					}
//				}
//			}
		}
	}
}